"use strict";
module.exports = {
  /**
   * 获取用户待办数据
   * @url client/note/kh/getNoteList 前端调用的url参数地址
   * data 请求参数
   * @param {String} params1  参数1
   */
  main: async (event) => {
    let { data = {}, userInfo, util, filterResponse, originalParam } = event;
    let { customUtil, uniID, config, pubFun, vk, db, _, $ } = util;
    let { uid } = data;
    // 业务逻辑开始-----------------------------------------------------------
    let { pageIndex, pageSize, status, classification_id } = data;

    // 参数校验
    if (pageIndex === undefined || pageIndex < 1) {
      return {
        code: -1,
        msg: "pageIndex参数必填且必须大于0",
      };
    }
    if (pageSize === undefined || pageSize < 1 || pageSize > 1000) {
      return {
        code: -1,
        msg: "pageSize参数必填且必须在1-1000之间",
      };
    }

    const whereJson = {
      user_id: uid,
    };
    if (classification_id) {
      whereJson.classification_id = classification_id;
    }
    // 添加状态筛选
    if (status !== undefined && status !== null && status !== "") {
      whereJson.status = status;
    }
    let noteList = await vk.baseDao.selects({
      dbName: "dfb-note",
      getCount: true,
      getMain: false,
      pageIndex,
      pageSize,
      whereJson,
      sortArr: [
        {
          name: "_add_time",
          type: "desc",
        },
      ],
      // 主表字段显示规则
      fieldJson: {
        title: true,
        content: true,
        _add_time_str: true,
        classification_id: true,
      },
      foreignDB: [
        {
          dbName: "dfb-classification",
          localKey: "classification_id",
          foreignKey: "_id",
          as: "classification",
          limit: 1,
          fieldJson: {
            name: true,
          },
        },
      ],
    });
    const stopLength = 150;
    noteList.rows.forEach((item) => {
      // 使用正则表达式匹配 < > 及其内部的内容并替换为空字符串
      let text = item.content
        .replace(/<[^>]*>/g, "")
        .substring(0, stopLength + 1);
      text =
        text.length > stopLength
          ? text.substring(0, stopLength) + "....."
          : text;
      let img = item.content.match(/<img[^>]*>/g);
      img = img ? img[0] : "";
      text = `<p>${text}</p>`;
      item.content = text + img;
      item.dateTime = item._add_time_str.substring(0, 16);
      delete item._add_time_str;
    });
    // 业务逻辑结束-----------------------------------------------------------
    return {
      code: 0,
      msg: "查询成功",
      data: noteList,
    };
  },
};
